﻿using Authentication.Model.Interface;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Contract.Authentication.Response;
using Common.Contract.Paging;
using Common.Contract.SystemConfig.Record;
using Common.Data.Repository.Enum;
using Common.Service.Command;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Authentication.Core.ServiceCommand.ChangeDao
{
    public class RetrieveListChangeDaoForExportRequestServiceCommand : ProviderServiceCommand<IProviderFactory, RetrieveListChangeDaoRequestRequest, RetrieveListChangeDaoRequestResponse>
    {

        public int pageSize = 10, pageIndex = 0, totalRecord = 0;
        public string TextSearch;
        public FilterRecord Filter = null;
        private UserRecord currentUser;
        public RetrieveListChangeDaoForExportRequestServiceCommand(IProviderFactory providers) : base(providers) { }
        protected override void Validate(RetrieveListChangeDaoRequestRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (request.CurrentUser == null)
            {
                throw new ArgumentException("User record must be set", "request");
            }
            else
            {
                currentUser = request.CurrentUser;
            }
            Filter = Request.Filter;
        }

        protected override bool OnExecute(RetrieveListChangeDaoRequestResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            int pageSize = 0, pageIndex = 0, totalRecord = 0;
            var applicationKey = Request.Header.ApplicationKey;
            try
            {
                if (Request.Page != null)
                {
                    pageIndex = Request.Page.PageIndex ?? 0;
                    pageSize = Request.Page.PageSize ?? 0;
                }
                var listRequest = Providers.ChangeDao.RetrieveListChangeDaoRequest(out totalRecord, currentUser, Filter, pageSize, pageIndex);
                if (listRequest == null)
                {
                    response.ErrorMessage = string.Format("Can not found user with Dao={0}", currentUser.Dao);
                    isSuccess = false;
                }
                else
                {
                    var listChangeId = listRequest.Select(x => x.Id).ToList();
                    var listChangDaoCifRequest = Providers.ChangeDao.RetrieveChangeDaoCif(currentUser, listChangeId);

                    var listCif = listChangDaoCifRequest.Select(x => x.Cif).ToList();
                    var listProduct = Providers.ChangeDao.RetrieveListChangeDaoProductByCifChecked(listCif, listChangeId, true);
                    var listCustomer = Providers.Customer.RetrieveListCustomerByCif(listCif).ToDictionary(x => x.Cif);

                    if (listChangDaoCifRequest != null && listProduct != null && listProduct.Count > 0 && listChangDaoCifRequest.Count > 0)
                    {
                        List<ChangeDaoCifRecord> ListChangeDaoCifRecord = (from x in listChangDaoCifRequest
                                                                           join y in listProduct on x.Cif equals y.Cif into y1
                                                                           from y2 in y1.DefaultIfEmpty()
                                                                           group y2 by x into yg
                                                                           select new ChangeDaoCifRecord
                                                                           {
                                                                               Cif = yg.Key.Cif,
                                                                               NewDao = yg.Key.NewDao,
                                                                               OldDao = listCustomer[yg.Key.Cif].Dao,
                                                                               Id = yg.Key.Id,
                                                                               ChangeDaoId = yg.Key.ChangeDaoId,
                                                                               IsApproved = yg.Key.Status == (int)StatusChangeDaoCifEnum.Aproved,
                                                                               ListChangeDaoProduct = (yg.FirstOrDefault() == null) ? new List<ChangeDaoProductCheckedRecord>() : yg.Select(y => new ChangeDaoProductCheckedRecord
                                                                               {
                                                                                   Cif = y.Cif,
                                                                                   NoProduct = y.NoProduct,
                                                                                   TypeProduct = y.TypeProduct,
                                                                                   Dao = y.Dao,
                                                                                   DataDate = y.BusinessDate.ToString("dd/MM/YYYY")
                                                                               }).ToList()
                                                                           }).ToList();

                        List<ChangeDaoRequestRecord> records = listRequest.Select(x => new ChangeDaoRequestRecord
                        {
                            Id = x.Id,
                            Pic = x.Pic,
                            Branch = x.Branch.BranchNameSme,
                            BranchId = x.Branch.BranchId,
                            ListChangeDaoCif = ListChangeDaoCifRecord.Where(y => y.ChangeDaoId == x.Id).ToList(),
                            CreatedDate = x.CreatedDate,
                            RejectPerson = string.IsNullOrEmpty(x.RejectPerson) ? string.Empty : x.RejectPerson,
                            ReasonDescription = string.IsNullOrEmpty(x.ReasonDescription) ? string.Empty : x.ReasonDescription,
                            Status = x.Status,
                            Reason = x.Reason
                        }).ToList();
                        response.Records = records;
                        response.Page = new PageRecord
                        {
                            PageIndex = pageIndex,
                            PageSize = pageSize,
                            TotalRecords = totalRecord,
                        };
                    }
                    else
                    {
                        response.ErrorMessage = string.Format("Can not found any request");
                        isSuccess = false;
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                response.ErrorMessage = string.Format("Can not found user with Dao={0}", Request.CurrentUser.Dao);
                response.IsSuccess = false;
            }
            return isSuccess;
        }
    }
}
